package com.myrpc.consumer.discovery.zk;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.myrpc.common.sessionchannel.Session;
import com.myrpc.consumer.netty.NettyClient;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class LoadBalanceChannelSession {

	private AtomicInteger roundRobin = new AtomicInteger(0);
	@Autowired
	NettyClient nettyClient;
	@Autowired
	ChannelSessionManager channelSessionManager;

	public Session chooseChannel(String className) {

		ConcurrentHashMap<String, Map<String, Session>> channelSession = channelSessionManager.getChannelSession();
		Map<String, Session> sessionmap;
		if (channelSession.size() != 1) {
			int size = channelSession.size();
			int index = (roundRobin.getAndAdd(1) + size) % size;
			Object[] array = channelSession.values().toArray();
			 sessionmap = (Map<String, Session>) array[index];
		} else {
			sessionmap = channelSession.entrySet().iterator().next().getValue();
		}
		Session session = sessionmap.get(className);
		return session;
	}

}
